package org.weed.remote.util;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

import javax.imageio.ImageIO;

public class ByteUtils {
	
	// ========== Other -> HexString
	public static String toHexString(byte b) {
		char[] hexDigit = {
			'0', '1', '2', '3', '4', '5', '6', '7', 
			'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
		};
		char[] chars = { hexDigit[(b >> 4) & 0x0f], hexDigit[b & 0x0f] };
		return new String(chars);
	}
	
	public static String toHexString(char c) {
		byte high = (byte) (c >>> 8);
		byte low = (byte) (c & 0xff);
		return toHexString(high) + toHexString(low);
	}
	
	// ========== Other -> Bytes
	public static byte[] toBytes(int value) {
		return ByteBuffer.allocate(4).putInt(value).array();
	}
	
	public static byte[] toBytes(BufferedImage bufferedImage) throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ImageIO.write(bufferedImage, "png", baos);
		baos.flush();
		byte[] bytes = baos.toByteArray();
		baos.close();
		return bytes;
	}
	
	// ========== Bytes -> Other
	public static int toInt(byte[] bytes) {
		return ((bytes[0] & 0xff) << 24) | ((bytes[1] & 0xff) << 16) | ((bytes[2] & 0xff) << 8) | (bytes[3] & 0xff); 
	}
	
	public static BufferedImage toBufferedImage(byte[] bytes) throws Exception {
		ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
		return ImageIO.read(bais);
	}
	
	// ==========
	public static void printBytes(byte[] bytes) {
		StringBuilder builder = new StringBuilder();
		builder.append("0x");
	    for (int i = 0; i < bytes.length; i++) {
	        builder.append(toHexString(bytes[i]));
	    }
	    System.out.println(builder.toString());
	}	
	
}
